package com.yinhai.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.yinhai.constant.Contact;
import com.yinhai.model.SMSBean;
import com.yinhai.service.ContactUserServiceImpl;

public class SMSDaoImpl {

	public static final String CONTENT_URI_SMS = "content://sms"; // ����
	public static final String CONTENT_URI_SMS_INBOX = "content://sms/inbox";// �ռ���
	public static final String CONTENT_URI_SMS_SENT = "content://sms/sent"; // ����
	public static final String CONTENT_URI_SMS_CONVERSATIONS = "content://sms/conversations";

	public SMSDaoImpl(Context mContext) {
		this.mContext = mContext;
		// TODO Auto-generated constructor stub
	}

	public static String[] SMS_COLUMNS = new String[] { "_id", // 0
			"thread_id", // 1
			"address", // 2
			"person", // 3
			"date", // 4
			"body", // 5
			"read", // 6; 0:not read 1:read; default is 0
			"type", // 7; 0:all 1:inBox 2:sent 3:draft 4:outBox 5:failed
					// 6:queued
			"service_center" // 8
	};
	public static String[] THREAD_COLUMNS = new String[] { "thread_id",
			"msg_count", "snippet" };

	private Context mContext;

	public String getContentUris() {
		String rtn = "{";
		rtn += "\"sms\":\"" + CONTENT_URI_SMS + "\"";
		rtn += ",\"inbox\":\"" + CONTENT_URI_SMS_INBOX + "\"";
		rtn += ",\"sent\":\"" + CONTENT_URI_SMS_SENT + "\"";
		rtn += ",\"conversations\":\"" + CONTENT_URI_SMS_CONVERSATIONS + "\"";
		rtn += "}";
		return rtn;
	}

	public String get(int number) {
		return getData(null, number);
	}

	public String getUnread(int number) {
		return getData("type=1 AND read=0", number);
	}

	public String getRead(int number) {
		return getData("type=1 AND read=1", number);
	}

	public String getInbox(int number) {
		return getData("type=1", number);
	}

	public String getSent(int number) {
		return getData("type=2", number);
	}

	public String getByThread(int thread) {
		return getData("thread_id=" + thread, 0);
	}

	public String getData(String selection, int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			if (number > 0) {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
						SMS_COLUMNS, selection, null, "date desc limit "
								+ number);
			} else {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
						SMS_COLUMNS, selection, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0)
				return "[]";
			String rtn = "";
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				if (i > 0)
					rtn += ",";
				rtn += "{";
				rtn += "\"_id\":" + cursor.getString(0);
				rtn += ",\"thread_id\":" + cursor.getString(1);
				rtn += ",\"address\":\"" + cursor.getString(2) + "\"";
				rtn += ",\"person\":\""
						+ ((cursor.getString(3) == null) ? "" : cursor
								.getString(3)) + "\"";
				rtn += ",\"date\":" + cursor.getString(4);
				rtn += ",\"body\":\"" + cursor.getString(5) + "\"";
				rtn += ",\"read\":"
						+ ((cursor.getInt(6) == 1) ? "true" : "false");
				rtn += ",\"type\":" + cursor.getString(7);
				rtn += ",\"service_center\":" + cursor.getString(8);
				rtn += "}";
			}
			if (!cursor.isClosed()) {
				cursor.close();
			}
			return "[" + rtn + "]";
		} catch (Exception e) {
			return "[]";
		}
	}

	public List<SMSBean> getThreads(int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		List<SMSBean> list = new ArrayList<SMSBean>();
		try {
			if (number > 0) {
				cursor = contentResolver.query(
						Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
						THREAD_COLUMNS, null, null, "thread_id desc limit "
								+ number);
			} else {
				cursor = contentResolver.query(
						Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
						THREAD_COLUMNS, null, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0)
				return list;
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				SMSBean mmt = new SMSBean(cursor.getString(0),
						cursor.getString(1), cursor.getString(2));
				list.add(mmt);
			}
			if (!cursor.isClosed()) {
				cursor.close();
			}
			return list;
		} catch (Exception e) {
			return list;
		}
	}

	// 获取短消息列表的总条数
	public int getMsgCount() {
		Cursor cursor = null;
		int count = 0;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			cursor = contentResolver.query(
					Uri.parse("content://mms-sms/conversations?simple=true"),
					new String[] { "count(*)" }, "type=0", null, "date desc");

			if (cursor == null || cursor.getCount() == 0) {
				return 0;
			} else {
				count = cursor.getInt(0);
				if (!cursor.isClosed()) {
					cursor.close();
				}
				return count;
			}

		} catch (Exception e) {
			return 0;
		}finally{
			if (cursor !=null) {
				cursor.close();
			}
		}
	}

	public List<SMSBean> getThreadsPage(int page) {
		Cursor cursor = null;
		Cursor cursorPhone = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		List<SMSBean> list = new ArrayList<SMSBean>();
		try {
//			cursor = contentResolver.query(
//					Uri.parse(CONTENT_URI_SMS_CONVERSATIONS), THREAD_COLUMNS,
//					null, null, "date desc limit " + page * Contact.LIMIT + ","
//							+ Contact.LIMIT);
			cursor = contentResolver.query(
					Uri.parse("content://mms-sms/conversations?simple=true"), new String[]{"_id","message_count","snippet","date","recipient_ids","snippet_cs from threads where type=0 order by date desc limit " +page * Contact.LIMIT + ","
						+ Contact.LIMIT +"--" },
					null , null, null);
			if (cursor == null || cursor.getCount() == 0)
				return list;
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				SMSBean mmt = new SMSBean(cursor.getString(0),
						cursor.getString(1), cursor.getString(2),cursor.getLong(3));
				// 内容不为空
				if(cursor.getString(2) !=null && !cursor.getString(2).equals("null") &&!cursor.getString(2).equals("") ) {
			    
					cursorPhone = mContext.getContentResolver().query(Uri.parse("content://mms-sms/canonical-addresses")
							, new String[]{"_id","address"}, " _id="+cursor.getString(4), null, null);
					
					cursorPhone.moveToFirst();
					mmt.setName(cursorPhone.getString(1));
					mmt.setAddress(cursorPhone.getString(1));
					
					if (ContactUserServiceImpl.phoneNames.get(mmt.getAddress().indexOf("+86")==0?mmt.getAddress().substring(3, mmt.getAddress().length()):mmt.getAddress()) == null) {
						mmt.setName(cursorPhone.getString(1));// 电话号码
					} else {
						mmt.setName(ContactUserServiceImpl.phoneNames.get(mmt.getAddress().indexOf("+86")==0?mmt.getAddress().substring(3, mmt.getAddress().length()):mmt.getAddress()));
					}
					
					if(cursor.getString(5).equals("106")){
						if(null != mmt.getMsg_snippet()) {
							mmt.setMsg_snippet(new String(mmt.getMsg_snippet().getBytes("ISO8859_1"),"utf-8"));
						}
					}
					
					cursorPhone.close();
				/*}else{
					
				}*/
				/*ContentResolver contentnew = mContext.getContentResolver();
				Uri uri = Uri.parse("content://mms");
				String[] projection = new String[] { "_id" }; // 查询的列
				Cursor cursornew = null;
				cursornew = contentnew.query(uri, projection, "thread_id = "
						+ mmt.getThread_id(), null, "date asc");
				if (cursornew != null && cursornew.getCount() > 0) {
					mmt.setMsg_count((Integer.parseInt(mmt.getMsg_count()) + cursornew
							.getCount()) + "");
				}
				
				if (!cursornew.isClosed()) {
					cursornew.close();
				}*/
				
				list.add(mmt);
				}
				
				
			}
			
			if (!cursor.isClosed()) {
				cursor.close();
			}
			
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return list;
		}finally{
//			if (cursor!=null) {
				cursor.close();
//			}
		}
	}
	
	

	public List<SMSBean> getThreadsNum(List<SMSBean> ll) {
		List<SMSBean> list = new ArrayList<SMSBean>();
		try {
			Cursor cursor = null;
			ContentResolver contentResolver = mContext.getContentResolver();
			// try {
			for (SMSBean mmt : ll) {
				
				try {
					cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
							SMS_COLUMNS, "thread_id = " + mmt.getThread_id(),
							null, null);
					if (!(cursor == null || cursor.getCount() == 0)) {
						cursor.moveToFirst();
						mmt.setAddress(cursor.getString(2));
						
						// if(cursor.getString(3) == null) {
						// //陌生人
						// mmt.setName(cursor.getString(2));
						// } else {
						// //在通讯录中的
						// mmt.setName(cursor.getString(3));
						// }
						if (mmt.getAddress() == null || mmt.getAddress().equals("null") || mmt.getAddress().equals("")) {
							String testThread = mmt.getThread_id();
							// 草稿箱数据
							Cursor cursor1 = contentResolver
									.query(Uri
											.parse("content://mms-sms/conversations?simple=true"),
											new String[] { "recipient_ids" },
											"_id=" + mmt.getThread_id(), null, null);
							cursor1.moveToFirst();
							
							String k = cursor1.getString(0);
							try {
								Cursor cursor2 = contentResolver
										.query(Uri
												.parse("content://mms-sms/canonical-addresses"),
												new String[] { "address" }, "_id="
														+ cursor1.getString(0), null,
												null);
								cursor2.moveToFirst();
								mmt.setAddress(cursor2.getString(0));
								if (!cursor1.isClosed()) {
									cursor1.close();
								}
								if (!cursor2.isClosed()) {
									cursor2.close();
								}
							} catch(Exception e) {
								e.printStackTrace();
							}
							
							
							
							
						}
						if (ContactUserServiceImpl.phoneNames.get(mmt.getAddress().indexOf("+86")==0?mmt.getAddress().substring(3, mmt.getAddress().length()):mmt.getAddress()) == null) {
							mmt.setName(cursor.getString(2));// 电话号码
						} else {
							mmt.setName(ContactUserServiceImpl.phoneNames.get(mmt.getAddress().indexOf("+86")==0?mmt.getAddress().substring(3, mmt.getAddress().length()):mmt.getAddress()));
						}
						mmt.setDate(cursor.getLong(4));
						mmt.setRead(cursor.getString(6));
						if (!cursor.isClosed()) {
							cursor.close();
						}
					}
					list.add(mmt);
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					if (cursor!=null) {
						cursor.close();
					}
					
				}
			}
			return list;
		} catch (Exception e) {
			return list;
		}

	}
}
